"""
自定义异常模块
定义项目专用的异常类
"""

class SteHubException(Exception):
    """
    SteHub 异常基类
    所有自定义异常的基类
    """
    
    def __init__(self, message: str = "发生错误", 
                 code: str = "INTERNAL_ERROR",
                 status_code: int = 500,
                 details: dict = None):
        """
        初始化异常
        
        Args:
            message: 错误消息
            code: 错误代码
            status_code: HTTP状态码
            details: 错误详情
        """
        self.message = message
        self.code = code
        self.status_code = status_code
        self.details = details or {}
        super().__init__(self.message)
    
    def to_dict(self) -> dict:
        """
        转换为字典格式
        
        Returns:
            dict: 异常信息字典
        """
        return {
            'error': True,
            'code': self.code,
            'message': self.message,
            'details': self.details
        }
    
    def __str__(self) -> str:
        return f"[{self.code}] {self.message}"

class ValidationError(SteHubException):
    """数据验证错误"""
    
    def __init__(self, message: str = "数据验证失败", 
                 details: dict = None):
        super().__init__(
            message=message,
            code="VALIDATION_ERROR",
            status_code=400,
            details=details
        )

class AuthenticationError(SteHubException):
    """认证错误"""
    
    def __init__(self, message: str = "认证失败", 
                 details: dict = None):
        super().__init__(
            message=message,
            code="AUTHENTICATION_ERROR",
            status_code=401,
            details=details
        )

class AuthorizationError(SteHubException):
    """授权错误"""
    
    def __init__(self, message: str = "权限不足", 
                 details: dict = None):
        super().__init__(
            message=message,
            code="AUTHORIZATION_ERROR",
            status_code=403,
            details=details
        )

class ResourceNotFoundError(SteHubException):
    """资源未找到错误"""
    
    def __init__(self, message: str = "资源未找到", 
                 resource_type: str = None,
                 resource_id: str = None):
        details = {}
        if resource_type:
            details['resource_type'] = resource_type
        if resource_id:
            details['resource_id'] = resource_id
            
        super().__init__(
            message=message,
            code="RESOURCE_NOT_FOUND",
            status_code=404,
            details=details
        )

class StorageError(SteHubException):
    """存储错误"""
    
    def __init__(self, message: str = "存储操作失败", 
                 operation: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if operation:
            details['operation'] = operation
            
        super().__init__(
            message=message,
            code="STORAGE_ERROR",
            status_code=500,
            details=details
        )

class APIError(SteHubException):
    """API错误"""
    
    def __init__(self, message: str = "API调用失败", 
                 endpoint: str = None,
                 status_code: int = 500,
                 details: dict = None):
        if details is None:
            details = {}
        if endpoint:
            details['endpoint'] = endpoint
            
        super().__init__(
            message=message,
            code="API_ERROR",
            status_code=status_code,
            details=details
        )

class DatabaseError(SteHubException):
    """数据库错误"""
    
    def __init__(self, message: str = "数据库操作失败", 
                 operation: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if operation:
            details['operation'] = operation
            
        super().__init__(
            message=message,
            code="DATABASE_ERROR",
            status_code=500,
            details=details
        )

class NetworkError(SteHubException):
    """网络错误"""
    
    def __init__(self, message: str = "网络连接失败", 
                 service: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if service:
            details['service'] = service
            
        super().__init__(
            message=message,
            code="NETWORK_ERROR",
            status_code=503,
            details=details
        )

class ConfigurationError(SteHubException):
    """配置错误"""
    
    def __init__(self, message: str = "配置错误", 
                 config_key: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if config_key:
            details['config_key'] = config_key
            
        super().__init__(
            message=message,
            code="CONFIGURATION_ERROR",
            status_code=500,
            details=details
        )

class RateLimitError(SteHubException):
    """速率限制错误"""
    
    def __init__(self, message: str = "请求过于频繁", 
                 limit: int = None,
                 reset_time: int = None,
                 details: dict = None):
        if details is None:
            details = {}
        if limit:
            details['limit'] = limit
        if reset_time:
            details['reset_time'] = reset_time
            
        super().__init__(
            message=message,
            code="RATE_LIMIT_EXCEEDED",
            status_code=429,
            details=details
        )

class FileUploadError(SteHubException):
    """文件上传错误"""
    
    def __init__(self, message: str = "文件上传失败", 
                 filename: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if filename:
            details['filename'] = filename
            
        super().__init__(
            message=message,
            code="FILE_UPLOAD_ERROR",
            status_code=400,
            details=details
        )

class EmailError(SteHubException):
    """邮件发送错误"""
    
    def __init__(self, message: str = "邮件发送失败", 
                 recipient: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if recipient:
            details['recipient'] = recipient
            
        super().__init__(
            message=message,
            code="EMAIL_ERROR",
            status_code=500,
            details=details
        )

class ChatError(SteHubException):
    """聊天错误"""
    
    def __init__(self, message: str = "聊天功能错误", 
                 room_id: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if room_id:
            details['room_id'] = room_id
            
        super().__init__(
            message=message,
            code="CHAT_ERROR",
            status_code=500,
            details=details
        )

class ForumError(SteHubException):
    """论坛错误"""
    
    def __init__(self, message: str = "论坛功能错误", 
                 post_id: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if post_id:
            details['post_id'] = post_id
            
        super().__init__(
            message=message,
            code="FORUM_ERROR",
            status_code=500,
            details=details
        )

class RealTimeError(SteHubException):
    """实时通信错误"""
    
    def __init__(self, message: str = "实时通信错误", 
                 connection_id: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if connection_id:
            details['connection_id'] = connection_id
            
        super().__init__(
            message=message,
            code="REALTIME_ERROR",
            status_code=500,
            details=details
        )

class ThirdPartyServiceError(SteHubException):
    """第三方服务错误"""
    
    def __init__(self, message: str = "第三方服务错误", 
                 service: str = None,
                 details: dict = None):
        if details is None:
            details = {}
        if service:
            details['service'] = service
            
        super().__init__(
            message=message,
            code="THIRD_PARTY_SERVICE_ERROR",
            status_code=502,
            details=details
        )

def handle_exception(exception: Exception) -> tuple:
    """
    统一异常处理
    
    Args:
        exception: 异常对象
        
    Returns:
        tuple: (响应字典, HTTP状态码)
    """
    from flask import jsonify
    
    if isinstance(exception, SteHubException):
        # 处理自定义异常
        response = exception.to_dict()
        status_code = exception.status_code
    else:
        # 处理未知异常
        response = {
            'error': True,
            'code': 'INTERNAL_ERROR',
            'message': '服务器内部错误',
            'details': {}
        }
        status_code = 500
        
        # 在开发环境中显示详细错误信息
        import os
        if os.environ.get('FLASK_ENV') == 'development':
            response['details']['debug'] = str(exception)
    
    return jsonify(response), status_code

def create_validation_error(field: str, message: str, value: any = None) -> ValidationError:
    """
    创建验证错误
    
    Args:
        field: 字段名
        message: 错误消息
        value: 字段值
        
    Returns:
        ValidationError: 验证错误对象
    """
    details = {
        'field': field,
        'message': message
    }
    if value is not None:
        details['value'] = value
    
    return ValidationError(
        message=f"字段 '{field}' 验证失败: {message}",
        details=details
    )

def create_resource_not_found(resource_type: str, resource_id: str) -> ResourceNotFoundError:
    """
    创建资源未找到错误
    
    Args:
        resource_type: 资源类型
        resource_id: 资源ID
        
    Returns:
        ResourceNotFoundError: 资源未找到错误对象
    """
    return ResourceNotFoundError(
        message=f"{resource_type} '{resource_id}' 未找到",
        resource_type=resource_type,
        resource_id=resource_id
    )